package top.kaoshanji.p1ch03b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 代码清单 p1ch03b-12：基于zip/jar文件系统实现的添加新文件到已有zip文件的做法
 * author kaoshanji
 * ^_^
 * create time 2025/1/11 19:05
 */
public class FileSystemExample01 {

    private static final Logger logger = LogManager.getLogger(FileSystemExample01.class);

    public static void main(String[] args) {
        logger.info("...代码清单 p1ch03b-12：基于zip/jar文件系统实现的添加新文件到已有zip文件的做法...");

        File zipFile = Paths.get(FileConstant.LOCAL_ROOT_PATH.concat("p1ch03b12-我是压缩文件.zip")).toFile();
        File fileToAdd = Paths.get(FileConstant.LOCAL_ROOT_PATH.concat("p1ch03b12-我是新文件.txt")).toFile();

        Map<String, String> env = new HashMap<>(1);
        env.put("create", "true");

        try (FileSystem fs = FileSystems.newFileSystem(URI.create("jar:" + zipFile.toURI()), env)){
            Path pathToAddFile = fileToAdd.toPath();
            Path pathInZipfile = fs.getPath("/" + fileToAdd.getName());

            // 核心代码..
            Files.copy(pathToAddFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
